/* eslint-disable */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { ACCESS_TOKEN, HTTP_STATUS_CODE } from '@/utils/vars'

const createSever = ({ baseURL }) => {
  const service = axios.create({
    baseURL,
    withCredentials: true, // 添加cookie
    timeout: 5000
  })

  service.interceptors.request.use(
    config => {
      if (store.getters.token) {
        config.headers[ACCESS_TOKEN] = store.getters.token
        // 禁止ie浏览器请求缓存
        if (!!window.ActiveXObject || 'ActiveXObject' in window) {
          config.headers['cache-control'] = 'no-cache'
          config.headers['Pragma'] = 'no-cache'
        }
      }
      return config
    },
    e => Promise.reject(e)
  )

  service.interceptors.response.use(
    async ({ headers, data }) => {
      const contentType = headers['content-type']
      // 如果不是json则直接返回data
      if (contentType && !/json/.test(contentType)) {
        return data
      }
      let res = data || {}
      if (res instanceof Blob && /json/.test(res.type)) {
        res = JSON.parse(await res.text())
      }
      if (parseInt(res.code) === 0 || parseInt(res.code) === 200) {
        return res
      } else {
        res.message = res.message || '接口没有返回任何消息，请联系管理员！'
        Message({ message: res.message, type: 'error' })
        return Promise.reject(new Error(res.message))
      }
    },
    error => {
      const { status } = error.response || { status: 0 }
      //未登录直接跳转首页
      if (status === UNAUTHORIZED) {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
        // MessageBox.confirm('你现在已经退出登录状态，是否重新登陆？', {
        //   confirmButtonText: '重新登陆',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // }).catch(() => {
        //   if (!store.getters['user/hasUserInfo']) {
        //     store.dispatch('user/resetToken').then(() => {
        //       location.reload()
        //     })
        //   }
        // })
      } else {
        Message({
          message: error.message,
          type: 'error'
        })
      }
      return Promise.reject(error)
    }
  )
  return service
}

export default createSever({
  baseURL: process.env.VUE_APP_BASE_API
})
